package com.hhl.flower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhl.flower.common.constant.UserConstant;
import com.hhl.flower.common.exception.BaseException;
import com.hhl.flower.common.utils.AliOssUtil;
import com.hhl.flower.common.utils.MinioUtil;
import com.hhl.flower.context.BaseContext;
import com.hhl.flower.mapper.UserMapper;
import com.hhl.flower.pojo.dto.UserLoginDTO;
import com.hhl.flower.pojo.dto.UserRegisterDTO;
import com.hhl.flower.pojo.entity.User;
import com.hhl.flower.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

/**
* @author Liubuzhu
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-05-21 18:43:49
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private AliOssUtil aliOssUtil;

	@Autowired
	private MinioUtil minioUtil;


	/**
	 * 用户登录
	 * @param userLoginDTO
	 * @return
	 */
	@Override
	public User login(UserLoginDTO userLoginDTO) {

		String username = userLoginDTO.getUsername();
		String password = userLoginDTO.getPassword();

		// 1、根据用户名查询数据库中的数据
		User user = userMapper.getByUsername(username);

		//2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
		if (user == null) {
			//账号不存在
			throw new BaseException("用户不存在！");
		}

		//密码比对
		//对前端传过来的明文密码进行md5加密处理
		password = DigestUtils.md5DigestAsHex(password.getBytes());
//		System.out.println("加密后的密码："+ password);
		if (!password.equals(user.getPassword())) {
			// 密码错误
			throw new BaseException("密码错误！");
		}

		//3、返回实体对象
		return user;

	}

	/**
	 * 新增用户
	 * @param userRegisterDTO
	 */
	public void register(UserRegisterDTO userRegisterDTO) {

		String username = userRegisterDTO.getUsername();
		String password = userRegisterDTO.getPassword();

		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("username", username);
		User user = userMapper.selectOne(queryWrapper);   //查询数据库里值等于username并且没有注销的数据
		if (user != null) {
			throw new BaseException("账号/手机号/邮箱已存在！");
		}

		QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
		queryWrapper1.orderByDesc("id").last("limit 1");    // 降序选第一个
		User last_user = userMapper.selectOne(queryWrapper1);
		int new_user_uid;
		if (last_user == null) {
			new_user_uid = 1;
		} else {
			new_user_uid = last_user.getId() + 1;
		}

		//对前端传过来的明文密码进行md5加密处理
		password = DigestUtils.md5DigestAsHex(password.getBytes());

		User registerUser = new User();
		//对象属性拷贝
		BeanUtils.copyProperties(userRegisterDTO, registerUser);

		registerUser.setPassword(password);

		//设置默认的信息
		registerUser.setNickname("用户_" + new_user_uid);
		registerUser.setAvatar("1.jpg");
		registerUser.setGender(UserConstant.UNKNOWN);
		registerUser.setDescription("这个人很懒，什么都没写~");
		registerUser.setVip(0);
		registerUser.setPoint(0);
		registerUser.setRole(0);
		registerUser.setCreateDate(LocalDateTime.now());

		userMapper.insert(registerUser);
	}

	public void updateUserInfo(User user) {

		Integer uId = BaseContext.getCurrentId();
		String nickname = user.getNickname();
		String description = user.getDescription();
		String phone = user.getPhone();
		String email = user.getEmail();
		Integer gender = user.getGender();
		String avatar = user.getAvatar();

		if (nickname == null || nickname.trim().isEmpty()) {
			throw new BaseException("昵称不能为空");
		}
		if (nickname.length() > 24 || description.length() > 100) {
			throw new BaseException("输入字符过长");
		}

		// 查重
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("nickname", nickname).ne("id", uId);
		User user1 = userMapper.selectOne(queryWrapper);
		if (user1 != null) {
			throw new BaseException("该昵称已被其他用户占用");
		}

		QueryWrapper<User> queryWrapper2 = new QueryWrapper<>();
		queryWrapper2.eq("phone", phone).ne("id", uId);
		User user2 = userMapper.selectOne(queryWrapper2);
		if (user2 != null) {
			throw new BaseException("该手机号已被注册");
		}

		QueryWrapper<User> queryWrapper3 = new QueryWrapper<>();
		queryWrapper3.eq("email", email).ne("id", uId);
		User user3 = userMapper.selectOne(queryWrapper3);
		if (user3 != null) {
			throw new BaseException("该邮箱已被注册");
		}

		UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("id", uId)
				.set("nickname", nickname)
				.set("description", description)
				.set("phone", phone)
                .set("email", email)
                .set("gender", gender)
                .set("avatar", avatar);
		userMapper.update(null, updateWrapper);
	}

	public String updateUserAvatar (Integer uId, MultipartFile file) throws IOException {
		log.info("文件上传:{}", file);
		// 原始文件名
		String originalFilename = file.getOriginalFilename();
		// 截取原始文件名的后缀
		String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
		// 构造新文件名称
		String objectName = UUID.randomUUID().toString() + extension;
		// 文件的请求路径
			String filePath = aliOssUtil.upload(file.getBytes(), "avatar", objectName);
//		String filePath = minioUtil.upload(file, "avatar", objectName);
		// TODO 后期打算首先判断文件是否存在，存在即删除后在上传
		// 更新数据库
		UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("id", uId).set("avatar", filePath);
		userMapper.update(null, updateWrapper);

		return filePath;
	}

}




